package com.hao.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class ShiroConfig {

    // Subject
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); //设置安全管理器

        //添加过滤器
        /**
         * anon:无需认证就可以访问
         * authc: 必须认证才能访问
         * user: 必须拥有记住我才能访问
         * perms: 拥有对某个资源权限才能访问
         * role: 拥有某个角色权限才能访问
         * */
        Map map = new LinkedMap();
        //map.put("/ml","perms[user:1]");
        map.put("/ml","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/out"); //如果被拦截了就会跳到login页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("/error"); //点击没有权限的就会跳转错误页面
        return shiroFilterFactoryBean;
    }


    // SecurityManger
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("Realm") UserRealm userRealm){
        DefaultWebSecurityManager SecurityManger = new DefaultWebSecurityManager();
        SecurityManger.setRealm(userRealm); //关联Realm
        return SecurityManger;
    }

    //Realm
    @Bean(name="Realm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
    //整合shiro和thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}
